package com.elock.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.elock.base.core.Filter;
import com.elock.base.core.Pageable;
import com.elock.base.core.controller.BaseController;
import com.elock.base.core.controller.ResultMsg;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.JsonUtils;
import com.elock.entity.Car;
import com.elock.entity.CarSaleOrg;
import com.elock.entity.ElockCar;
import com.elock.entity.SaleOrg;
import com.elock.entity.SystemDict;
import com.elock.entity.TerminalSaleOrg;
import com.elock.service.CarSaleOrgService;
import com.elock.service.CarService;
import com.elock.service.ElectronicFenceSaleOrgService;
import com.elock.service.ElockCarService;
import com.elock.service.MemberSaleOrgBaseService;
import com.elock.service.MemberService;
import com.elock.service.SaleOrgBaseService;
import com.elock.service.SystemDictBaseService;
import com.elock.service.TerminalSaleOrgService;

/**
 * Controller - 机构
 * 
 * @author 仁德
 */
@Controller("SaleOrgController")
@RequestMapping("/saleOrg")
public class SaleOrgController extends BaseController {

	@Resource(name = "saleOrgBaseServiceImpl")
	private SaleOrgBaseService saleOrgBaseService;
	@Resource(name = "systemDictBaseServiceImpl")
	private SystemDictBaseService systemDictBaseService;
	@Resource(name = "carSaleOrgServiceImpl")
	private CarSaleOrgService carSaleOrgService;
	@Resource(name = "carServiceImpl")
	private CarService carService;
	@Resource(name = "elockCarServiceImpl")
	private ElockCarService elockCarService;
	@Resource(name = "terminalSaleOrgServiceImpl")
	private TerminalSaleOrgService terminalSaleOrgService;
	@Resource(name = "electronicFenceSaleOrgServiceImpl")
	private ElectronicFenceSaleOrgService electronicFenceSaleOrgService;
	@Resource(name = "memberSaleOrgBaseServiceImpl")
	private MemberSaleOrgBaseService memberSaleOrgBaseService;
	@Resource(name = "memberServiceImpl")
	private MemberService memberService;

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Pageable pageable, ModelMap model) {

		return "/saleOrg/list";
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list_tb", method = RequestMethod.GET)
	public String list_tb(Pageable pageable, ModelMap model) {

		return "/saleOrg/list_tb";
	}

	/**
	 * 列表数据
	 */
	@RequestMapping(value = "/list_data", method = RequestMethod.POST)
	public @ResponseBody ResultMsg list_data(String saleOrgName, String sn, Boolean isEnabled, Pageable pageable,
			ModelMap model) {

		List<Map<String, Object>> saleOrgs = saleOrgBaseService.findList(saleOrgName, sn, isEnabled, pageable);
		String jsonPage = JsonUtils.toJson(saleOrgs);

		return ResultMsg.success(jsonPage);
	}

	/**
	 * 添加
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(Long ids, ModelMap model) {

		List<Filter> filters = new ArrayList<Filter>();
		filters.clear();
		filters.add(Filter.eq("code", "SaleOrgType"));
		filters.add(Filter.isNotNull("parent"));
		List<SystemDict> saleOrgTypes = systemDictBaseService.findList(null, filters, null);
		model.addAttribute("saleOrgTypes", saleOrgTypes);
		model.addAttribute("parent", saleOrgBaseService.getCurrentSaleOrg());

		return "/saleOrg/add";
	}

	/**
	 * 保存
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public @ResponseBody ResultMsg save(SaleOrg saleOrg, Long areaId, Long saleOrgId, HttpServletRequest request) {

		if(saleOrgBaseService.sameSaleOrgSn(saleOrg.getSn(), saleOrg.getId())>0){
			return error("该企业编号已存在，请重新维护");
		}
		
		if (saleOrgId != null) {
			SaleOrg so = saleOrgBaseService.find(saleOrgId);
			so.setIsLeaf(false);
			saleOrgBaseService.update(so);
			saleOrg.setParent(so);
		} else {

			List<Filter> filters = new ArrayList<Filter>();
			filters.add(Filter.eq("isTop", true));
			SaleOrg parent = saleOrgBaseService.find(filters);
			saleOrg.setParent(parent);

		}
		List<SaleOrg> saleOrgs = saleOrgBaseService.findChildren(null, null, saleOrg);
		if (saleOrgs != null && saleOrgs.size() == 0) {
			saleOrg.setIsLeaf(true);
		} else {
			saleOrg.setIsLeaf(false);
		}
		saleOrgBaseService.save(saleOrg);

		return success().addObjX(saleOrg.getId());
	}

	/**
	 * 编辑
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(Long id, ModelMap model) {

		model.addAttribute("saleOrg", saleOrgBaseService.find(id));
		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("code", "SaleOrgType"));
		filters.add(Filter.isNotNull("parent"));
		List<SystemDict> saleOrgTypes = systemDictBaseService.findList(null, filters, null);
		model.addAttribute("saleOrgTypes", saleOrgTypes);

		return "/saleOrg/edit";
	}

	/**
	 * 更新
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public @ResponseBody ResultMsg update(SaleOrg saleOrg, Long areaId, Long saleOrgId, HttpServletRequest request) {

		if(saleOrgBaseService.sameSaleOrgSn(saleOrg.getSn(), saleOrg.getId())>0){
			return error("该企业编号已存在，请重新维护");
		}
		List<SaleOrg> saleOrgs = saleOrgBaseService.findChildren(null, null, saleOrg);
		if (!saleOrg.getIsEnabled()) {
			for (SaleOrg so : saleOrgs) {
				so.setIsEnabled(false);
				saleOrgBaseService.update(so);
			}
		}

		if (saleOrgId != null) {
			SaleOrg so = saleOrgBaseService.find(saleOrgId);
			so.setIsLeaf(false);
			saleOrg.setParent(so);
			saleOrgBaseService.update(saleOrg, "uniqueIdentify", "budget", "lockBudget");
		} else {

			List<Filter> filters = new ArrayList<Filter>();
			filters.add(Filter.eq("isTop", true));
			SaleOrg parent = saleOrgBaseService.find(filters);
			saleOrg.setParent(parent);
			saleOrgBaseService.update(saleOrg, "parent", "uniqueIdentify", "budget", "lockBudget");
		}
		return success();
	}

	/**
	 * 删除
	 */
	// @RequestMapping(value = "/delete", method = RequestMethod.POST)
	// public @ResponseBody
	// ResultMsg delete(Long[] ids) {
	//
	// for (Long id : ids) {
	// SaleOrg saleOrg = saleOrgService.find(id);
	// if (saleOrg.getIsTop() != null && saleOrg.getIsTop()) {
	// return error("默认组织[" + saleOrg.getName() + "]不能删除！");
	// }
	// long count = storeService.count(Filter.eq("saleOrg", saleOrg));
	// if (count > 0) {
	// return error(saleOrg.getName() + " 已关联门店,不能删除！");
	// }
	// }
	// saleOrgService.delete(ids);
	// return success();
	// }

	/**
	 * 弹框查询组织列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/select_saleOrg", method = RequestMethod.GET)
	public String select_saleOrg(Pageable pageable, ModelMap model) {

		return "/saleOrg/select_saleOrg";
	}

	/**
	 * 弹框查询组织列表数据
	 */
	@RequestMapping(value = "/select_saleOrg_data", method = RequestMethod.POST)
	public @ResponseBody ResultMsg select_saleOrg_data(String name, String sn, Pageable pageable, ModelMap model) {

		List<Map<String, Object>> saleOrgs = saleOrgBaseService.findList(name, sn, true, pageable);
		String jsonPage = JsonUtils.toJson(saleOrgs);

		return ResultMsg.success(jsonPage);
	}

	@RequestMapping(value = "/getChildren", method = RequestMethod.POST)
	public @ResponseBody ResultMsg getChildren(Long id) {

		List<Map<String, Object>> saleOrgs = saleOrgBaseService.findChildren(id);
		return success().addObjX(saleOrgs);
	}

	/**
	 * 获取分类节点
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/getNodes", method = RequestMethod.POST)
	public @ResponseBody List<Object> getNodes(String id, String keyword, Integer stat) {
		List<Object> objs = new ArrayList<Object>();
		if (keyword != null) {

		} else {
			// type:0机构，1车辆，2锁，3钥匙
			SaleOrg saleOrg = null;
			Car car = null;
			if (!ConvertUtil.isEmpty(id)) {
				String[] ids = id.split("_");
				int type = Integer.parseInt(ids[0]);
				Long oid = Long.parseLong(ids[1]);
				if (type == 0) {
					saleOrg = saleOrgBaseService.find(oid);
				} else if (type == 1) {
					car = carService.find(oid);
				}
			}

			List<Filter> fis = new ArrayList<Filter>();
			if (saleOrg != null) {
				for (SaleOrg child : saleOrg.getChildren()) {
					if (child.getIsEnabled() != null && child.getIsEnabled()) {
						Map<String, Object> data = new HashMap<String, Object>();
						data.put("id", "0_" + child.getId());
						data.put("name", child.getName());
						data.put("isParent", !isLeaf(child, stat));
						data.put("type", 0);
						data.put("oid", child.getId());
						data.put("nocheck", true);
						objs.add(data);
					}
				}

				if (stat != null && stat == 1) {
					fis.clear();
					fis.add(Filter.eq("saleOrg", saleOrg));
					List<CarSaleOrg> carSaleOrgs = carSaleOrgService.findList(null, fis, null);
					for (CarSaleOrg carSaleOrg : carSaleOrgs) {
						Car cCar = carSaleOrg.getCar();
						Map<String, Object> data = new HashMap<String, Object>();
						data.put("id", "1_" + cCar.getId());
						data.put("name", cCar.getCarNumber());
						data.put("isParent", elockCarService.exists(Filter.eq("carId", cCar.getId())));
						data.put("type", 1);
						data.put("oid", cCar.getId());
						data.put("iconSkin", "car_online");
						data.put("nocheck", true);
						objs.add(data);
					}

					fis.clear();
					fis.add(Filter.eq("saleOrgId", saleOrg.getId()));
					List<TerminalSaleOrg> terminalSaleOrgs = terminalSaleOrgService.findList(null, fis, null);
					for (TerminalSaleOrg terminalSaleOrg : terminalSaleOrgs) {
						Map<String, Object> data = new HashMap<String, Object>();
						data.put("id", "3_" + terminalSaleOrg.getTerminalId());
						data.put("name", terminalSaleOrg.getTerminalNum());
						data.put("isParent", false);
						data.put("type", 3);
						data.put("oid", terminalSaleOrg.getTerminalId());
						data.put("iconSkin", "terminal_offline");
						data.put("nocheck", false);
						objs.add(data);
					}
				}
			} else if (car != null) {
				fis.clear();
				fis.add(Filter.eq("carId", car.getId()));
				List<ElockCar> elockCars = elockCarService.findList(null, fis, null);
				for (ElockCar elockCar : elockCars) {
					Map<String, Object> data = new HashMap<String, Object>();
					data.put("id", "2_" + elockCar.getElockId());
					data.put("name", elockCar.getPosition() + ConvertUtil.toEmpty(elockCar.getSeq()) + " "
							+ elockCar.getElockNum());
					data.put("isParent", false);
					data.put("type", 2);
					data.put("oid", elockCar.getElockId());
					data.put("iconSkin", "elock_offline");
					data.put("nocheck", false);
					objs.add(data);
				}
			} else {
				fis.clear();
				// fis.add(Filter.eq("member", memberService.getCurrent()));
				// MemberSaleOrg memberSaleOrg =
				// memberSaleOrgBaseService.find(fis);
				// SaleOrg child = memberSaleOrg.getSaleOrg();
				fis.add(Filter.isNull("parent"));
				fis.add(Filter.eq("isEnabled", true));
				for (SaleOrg child : saleOrgBaseService.findList(null, fis, null)) {
					Map<String, Object> data = new HashMap<String, Object>();
					data.put("id", "0_" + child.getId());
					data.put("name", child.getName());
					data.put("isParent", !isLeaf(child, stat));
					data.put("type", 0);
					data.put("oid", child.getId());
					data.put("nocheck", true);
					objs.add(data);
				}
			}
		}
		return objs;
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody ResultMsg delete(Long id, ModelMap model) {

		SaleOrg saleOrg = saleOrgBaseService.find(id);

		if (carSaleOrgService.exists(Filter.eq("saleOrg", saleOrg))) {
			return error("该机构存在与车辆的对应关系，无法删除");
		}
		// if (electronicFenceSaleOrgService.exists(Filter.eq("saleOrgId", id)))
		// {
		// return error("该机构存在与电子围栏的对应关系，无法删除");
		// }
		if (memberSaleOrgBaseService.exists(Filter.eq("saleOrg", saleOrg))) {
			return error("该机构存在与用户的对应关系，无法删除");
		}
		if (terminalSaleOrgService.exists(Filter.eq("saleOrgId", id))) {
			return error("该机构存在与终端设备的对应关系，无法删除");
		}
		if (saleOrg.getChildren() == null || saleOrg.getChildren().size() < 1) {
			saleOrgBaseService.deleteSaleOrg(saleOrg);
		} else {
			return error("该机构存在下级机构，无法删除");
		}

		return success();
	}

	private boolean isLeaf(SaleOrg saleOrg, Integer stat) {

		boolean isLeaf = true;
		if (stat != null && stat == 1) {
			boolean carExist = carSaleOrgService.exists(Filter.eq("saleOrg", saleOrg));
			boolean terminalExist = terminalSaleOrgService.exists(Filter.eq("saleOrgId", saleOrg.getId()));
			if (carExist || terminalExist) {
				isLeaf = false;
			} else {
				isLeaf = saleOrg.getIsLeaf();
			}
		} else {
			isLeaf = saleOrg.getIsLeaf();
		}
		return isLeaf;
	}
}
